package com.tj.admin.rest.stats;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Response;
import com.fqgj.common.api.annotations.ParamsValidate;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Lists;
import com.qianli.cashmama.product.facade.ProductFacade;
import com.qianli.cashmama.product.facade.result.ProductCategory;
import com.tj.admin.auth.vo.RequestLocalInfo;
import com.tj.admin.rest.ModuleResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 定向查询
 * Created with IntelliJ IDEA.
 * User: pavan
 * Date: 2019/4/26
 * Time: 下午2:02
 */
@RestController
@RequestMapping("/bizStats")
public class StatsController {

    private static final Log LOGGER = LogFactory.getLog(StatsController.class);

    private final String KEY_LIST = "KeyList";


    @Autowired
    private BizStatsSqlService bizStatsSqlService;


    @Autowired
    private ProductFacade productFacade;

    /**
     * 通用查询接口
     *
     * @param request
     * @return
     */
    @RequestMapping("/general/query")
    @ParamsValidate
    public ModuleResponse generalQuery(@RequestBody JSONObject request) {
        String queryKey = request.getString("queryKey");
        List<String> list = Lists.newArrayList(queryKey);
        Map<String, Object> paramsMap = JSON.parseObject(JSON.toJSONString(request), Map.class);
        Object startDate = paramsMap.get("startDate");
        if (startDate != null) {
            paramsMap.put("startDate", startDate.toString().substring(0, 10));
        }

        Object endDate = paramsMap.get("endDate");
        if (endDate != null) {
            paramsMap.put("endDate", endDate.toString().substring(0, 10));
        }

        paramsMap.put("merchantCode", RequestLocalInfo.getCurrentUser().getMerchantCode());
//        paramsMap.put("productCategory", RequestLocalInfo.getCurrentUser().getProductCategory());
        LOGGER.info("== generalQuery ==,queryKey:{},params:{}", queryKey, paramsMap);

        Response<List<ProductCategory>> allActiveProductCategoryByMerchantCode = productFacade.getProductCategoriesByMerchantCode(RequestLocalInfo.getCurrentUser().getMerchantCode());
        if (allActiveProductCategoryByMerchantCode == null || CollectionUtils.isEmpty(allActiveProductCategoryByMerchantCode)) {
            return new ModuleResponse();
        }
        try {
            List<String> productCategories = allActiveProductCategoryByMerchantCode.getData().parallelStream().map(ProductCategory::getCode).collect(Collectors.toList());
            String cat = "";
            for (String cate : productCategories) {
                cat = cat + "'" + cate + "',";
            }

            String substring = cat.substring(0, cat.length() - 1);

            paramsMap.put("categories", substring);
        } catch (Exception e) {
            LOGGER.error("== stats sql ==", e);
        }

        Map<String, Object> resultMap = this.getResult(list, paramsMap);
        return new ModuleResponse(resultMap);
    }

    private Map<String, Object> getResult(List<String> list, Map<String, Object> paramsMap) {
        Map<String, Object> resultMap = new HashMap<>();
        for (String str : list) {
            Object result = null;
            try {

                if (paramsMap.containsKey("loanType")) {
                    String loanType = paramsMap.get("loanType").toString();
                    if (loanType.equals("0")) {
                        result = bizStatsSqlService.getData(str + "Old88", paramsMap);
                    } else if (loanType.equals("0,1")) {
                        result = bizStatsSqlService.getData(str + "All88", paramsMap);
                    }


                }
                if (result == null) {
                    result = bizStatsSqlService.getData(str, paramsMap);
                }

                if (result == null) {
                    LOGGER.info("== result 为空 ==");
                } else {
                    LOGGER.info("== result  ==,result:{}", JSON.toJSONString(result));
                }

                JSONObject jsonObject = new JSONObject();
                if (result instanceof List) {
                    putResultToRespJson(jsonObject, str, (List<Map<String, Object>>) result);
                } else {
                    jsonObject = JSON.parseObject(JSON.toJSONString(result));
                }

                resultMap.putAll(jsonObject);
            } catch (Exception e) {
                LOGGER.error("查询统计数据失败,key:{},result:{}", str, JSON.toJSONString(result), e);
            }
        }
        return resultMap;
    }

    /**
     * 下划线转驼峰
     *
     * @param str
     * @return
     */
    private String lineToHump(String str) {
        if (str == null) {
            return "";
        }
        if (!str.contains("_")) {
            return str.substring(0, 1).toLowerCase() + str.substring(1);
        }
        Pattern linePattern = Pattern.compile("_(\\w)");
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    private void putResultToRespJson(JSONObject jsonObject, String str, List<Map<String, Object>> result) {
        if (result != null && ((List) result).size() > 0) {
            //找到size最大的map作为标题
            Map<String, Object> columnMap = (Map<String, Object>) ((List) result).get(0);
            for (Object object : (List) result) {
                Map<String, Object> map = (Map<String, Object>) object;
                if (map.size() > columnMap.size()) {
                    columnMap = map;
                }
            }
            //组装key列表 按序号排 例：01~date、02~number
            List<String> keyList = new ArrayList<>();
            for (String key : columnMap.keySet()) {
                keyList.add(key);
            }
            Collections.sort(keyList, new Comparator<String>() {
                @Override
                public int compare(String a, String b) {
                    return a.compareTo(b);
                }
            });
            for (int i = 0; i < keyList.size(); i++) {
                String[] tmp = keyList.get(i).split("~");
                keyList.set(i, tmp.length == 1 ? tmp[0] : tmp[1]);
            }
            jsonObject.put(lineToHump(str.replaceAll(" ", "_")) + KEY_LIST, keyList);
            //行实体的key 去除~
            List<Map<String, Object>> newResult = new ArrayList<>();
            for (Object object : (List) result) {
                Map<String, Object> map = (Map<String, Object>) object;
                Map<String, Object> temp = new HashMap<>();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String[] tmp = entry.getKey().split("~");
                    temp.put(tmp.length == 1 ? tmp[0] : tmp[1], entry.getValue());
                }
                newResult.add(temp);
            }
            jsonObject.put(lineToHump(str.replaceAll(" ", "_")), newResult);
        }
    }


}
